package com.vrv.app.cyberspace.modules.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.vrv.app.cyberspace.common.ddio.ApiV2Service;
import com.vrv.app.cyberspace.common.ddio.DDIORunnable;
import com.vrv.app.cyberspace.common.ddio.TemplateMessage;
import com.vrv.app.cyberspace.common.utils.HttpContextUtils;
import com.vrv.app.cyberspace.common.utils.JSONResult;
import com.vrv.app.cyberspace.config.WXBSystemConfig;
import com.vrv.app.cyberspace.modules.sys.entity.*;
import com.vrv.app.cyberspace.modules.sys.mapper.*;
import com.vrv.app.cyberspace.modules.sys.service.IRiskFeedbackTableService;
import com.vrv.app.cyberspace.modules.sys.service.IRiskManageTableService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sm
 * @since 2017-12-21
 */
@SuppressWarnings({"Duplicates", "SpringJavaInjectionPointsAutowiringInspection"})
@Service
@Transactional
public class RiskFeedbackTableServiceImpl extends ServiceImpl<RiskFeedbackTableMapper, RiskFeedbackTable> implements IRiskFeedbackTableService {
    Logger logger = LoggerFactory.getLogger(RiskFeedbackTableServiceImpl.class);

    @Autowired
    private RiskFeedbackTableMapper riskFeedbackTableMapper;
    @Autowired
    private IRiskManageTableService riskManageTableService;
    @Autowired
    private OrganizeTableMapper organizeTableMapper;
    @Autowired
    private RiskTypeTableMapper riskTypeTableMapper;
    @Autowired
    private UserTableMapper userTableMapper;
    @Autowired
    private CirculationRecordTableMapper circulationRecordTableMapper;
    @Autowired
    private ApiV2Service apiV2Service;
    @Autowired
    private WXBSystemConfig wxbSystemConfig;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");


    @Override
    public int submitRiskFeedback(RiskFeedbackTable riskFeedbackTable) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        Date date = new Date();
        riskFeedbackTable.setUserID(userTable.getLinkdoodID());
        riskFeedbackTable.setUpdateTime(date);
        if (1 == riskFeedbackTable.getStatus()) {//插入记录
            riskFeedbackTable.setExStatus(-1);
            insertRecord(riskFeedbackTable, userTable, date);
        }
        return riskFeedbackTableMapper.updateById(riskFeedbackTable);
    }

    private void insertRecord(RiskFeedbackTable riskFeedbackTable, UserTable userTable, Date date) {
        CirculationRecordTable circulationRecordTable = new CirculationRecordTable();
        circulationRecordTable.setTime(date);
        circulationRecordTable.setOperator(userTable.getLinkdoodName());
        circulationRecordTable.setfId(riskFeedbackTable.getId());
        circulationRecordTable.setContent(JSON.toJSONString(riskFeedbackTable));
        circulationRecordTableMapper.insert(circulationRecordTable);
    }

    @Override
    public RiskFeedbackTable detailRiskFeedback(RiskFeedbackTable rft) {
        //1.获取反馈信息
        RiskFeedbackTable riskFeedbackTable = riskFeedbackTableMapper.selectById(rft.getId());
        //2.更新查看状态
        UserTable readUser = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        riskFeedbackTable.setReadUserID(readUser.getLinkdoodID());
        riskFeedbackTable.setReadTime(new Date());
        riskFeedbackTableMapper.updateById(riskFeedbackTable);
        //3.获取详情
        riskFeedbackTable.setRiskManageTable(riskManageTableService.getRiskExtend(riskFeedbackTable.getBaseID()));
        riskFeedbackTable.setReadUser(readUser);
        if (riskFeedbackTable.getUserID() != null)
            riskFeedbackTable.setHandleUser(userTableMapper.selectById(riskFeedbackTable.getUserID()));
        //4.共下发多少家,反馈/未反馈数据量
        List<String> list = JSON.parseArray(riskFeedbackTable.getDownsSet(), String.class);
        if (list != null && list.size() > 0) {
            riskFeedbackTable.setTotalNum(list.size());
            riskFeedbackTable.setFeedbackNum(riskFeedbackTable.selectCount(new EntityWrapper<EventFeedbackTable>()
                    .eq("baseID", riskFeedbackTable.getBaseID())
                    .in("orgID", list)
                    .eq("status", 1)));
        }
        return riskFeedbackTable;
    }

    @Override
    public Page<RiskFeedbackTable> listRiskFeedback(RiskFeedbackTable riskFeedbackTable, Page<RiskFeedbackTable> page) {
        List<RiskFeedbackTable> riskFeedbackTables=new ArrayList<>();
        if(riskFeedbackTable.getStatus()!=null){
            riskFeedbackTables = riskFeedbackTableMapper.selectPage(page, new EntityWrapper<RiskFeedbackTable>().eq("orgID", riskFeedbackTable.getOrgID())
                    .eq("status", riskFeedbackTable.getStatus()).orderBy(true, "createTime", false));
        }
        if(riskFeedbackTable.getStatusList()!=null){//此逻辑是为了支持前端传递多个status进行查询--同时不改变PC端的逻辑
            List<Integer> statusList=JSON.parseArray(riskFeedbackTable.getStatusList(),Integer.class);
            riskFeedbackTables = riskFeedbackTableMapper.selectPage(page, new EntityWrapper<RiskFeedbackTable>().eq("orgID", riskFeedbackTable.getOrgID())
                    .in("status", statusList).orderBy(true,"status").orderBy(true, "createTime", false));
        }
        for (RiskFeedbackTable r : riskFeedbackTables) {
            r.setRiskManageTable(riskManageTableService.getRiskExtend(r.getBaseID()));
            if (r.getReadUserID() != null)
                r.setReadUser(userTableMapper.selectById(r.getReadUserID()));
            if (r.getUserID() != null)
                r.setHandleUser(userTableMapper.selectById(r.getUserID()));
        }
        page.setRecords(riskFeedbackTables);
        return page;
    }

    @Override
    public Page<RiskFeedbackTable> summary(RiskFeedbackTable riskFeedbackTable, Page<RiskFeedbackTable> page) {
        List<String> orgIDs = JSON.parseArray(riskFeedbackTable.getDownsSet(), String.class);
        Wrapper<RiskFeedbackTable> ew = new EntityWrapper<RiskFeedbackTable>()
                .eq("baseID", riskFeedbackTable.getBaseID())
                .in("orgID", orgIDs);
        List<RiskFeedbackTable> list = riskFeedbackTableMapper.selectPage(page, ew);
        OrganizeTable organization;
        for (RiskFeedbackTable e : list) {
            organization = organizeTableMapper.selectById(e.getOrgID());
            if (organization != null)
                e.setOrgName(organization.getOrgName());
            e.setHandleUser(userTableMapper.selectById(e.getUserID()));
            e.setReadUser(userTableMapper.selectById(e.getReadUserID()));
        }
        return page.setRecords(list);
    }

    @Override
    public JSONResult releaseEvent(RiskFeedbackTable rft) {
        JSONResult jsonResult = JSONResult.renderSuccess();
        //1.根据OrgID查询组织下的人员
        List<String> orgIDs = JSONArray.parseArray(rft.getDownsSet(), String.class);
        if (orgIDs != null && orgIDs.size() > 0) {
            try {
                List<UserTable> list = userTableMapper.selectList(new EntityWrapper<UserTable>().in("orgID", orgIDs));

                RiskFeedbackTable tem = riskFeedbackTableMapper.selectById(rft.getId());
                //2.创建反馈表
                RiskFeedbackTable riskFeedbackTable = new RiskFeedbackTable();
                riskFeedbackTable.setBaseID(tem.getBaseID());
                riskFeedbackTable.setCreateTime(new Date());
                for (String orgid : orgIDs) {
                    riskFeedbackTable.setOrgID(orgid);
                    riskFeedbackTableMapper.insert(riskFeedbackTable.clone());
                }

                List<String> toUsers = new ArrayList<>();
                for (UserTable u : list) {
                    toUsers.add(u.getLinkdoodID());
                }
                //3.记录下发单位
                tem.setDownsSet(rft.getDownsSet());
                tem.setReplyClaim(rft.getReplyClaim());
                riskFeedbackTableMapper.updateById(tem);
                //4.推送模板消息
                pushTemplateMessage(tem, toUsers);
            } catch (Exception e) {
                jsonResult = JSONResult.renderError();
                e.printStackTrace();
            }
        }
        return jsonResult;
    }

    @Override
    public JSONResult handleRiskFeedback(RiskFeedbackTable riskFeedbackTable) {
        RiskFeedbackTable tem = riskFeedbackTableMapper.selectById(riskFeedbackTable.getId());
        tem.setStatus(riskFeedbackTable.getStatus());
        return riskFeedbackTableMapper.updateById(tem) > 0 ? JSONResult.renderSuccess() : JSONResult.renderError();
    }

    @Override
    public RiskFeedbackTable total(RiskFeedbackTable riskFeedbackTable) {
        List<String> orgIDs = JSON.parseArray(riskFeedbackTable.getDownsSet(), String.class);
        return riskFeedbackTableMapper.total(riskFeedbackTable.getBaseID(), orgIDs);
    }

    private void pushTemplateMessage(RiskFeedbackTable rft, List<String> toUsers) {
        String appid = apiV2Service.getAppID();
        RiskManageTable rmt = riskManageTableService.selectById(rft.getBaseID());
        RiskTypeTable riskType = riskTypeTableMapper.selectById(rmt.getPrimaryRiskType());
        String content = "时间: " + dateFormat.format(new Date()) + "\n标题：" + rmt.getTitle() + "\n类别: " + riskType.getName() + "\n请您及时处理 ";
        TemplateMessage templateMessage = TemplateMessage.createOne(appid, "风险管理", appid, content, wxbSystemConfig.getRiskFeedbackDetailUrl() + "&id=" + rmt.getBaseID(),
                StringUtils.join(toUsers.toArray(), ','));
        try {
            executorService.execute(new DDIORunnable(apiV2Service, "sendTemplateMsg", templateMessage, TemplateMessage.class));
        } catch (NoSuchMethodException e) {
            logger.info("推送事件管理(ID" + rmt.getBaseID() + ")消息失败! ");
            e.printStackTrace();
        }
    }
}
